//输入一个整数N
//产生N个1-100的随机数
//通过管道接收
//计算随机数之和
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/wait.h>
#include <string.h>

#define PIPE_NAME "/tmp/myfifo"

char *MyGetString(char*pbuf,int size);

int main(int argc,char*argv[])
{
    int ret=0;
    int rfd=0;
    int size=0;
    char *p=NULL;
    char buf[64]="";
    if(access(PIPE_NAME,F_OK))
    {
        ret = mkfifo(PIPE_NAME,0666);
        if (ret<0)
        {
            printf("error");
            return 1;
        }
        
    }
    printf("read process before open\n");
    rfd = open(PIPE_NAME,O_RDONLY);
    printf("read process after open\n");
    if(rfd < 0)
    {
        printf("error");
        return 2;
    }
    while (1)
    {
        read(rfd,&size,sizeof(int));
        p=malloc(size);
        if(NULL == p)
        {
            printf("Malloc Failed\n");
            break;
        }
        memset(p,0,size);
        read(rfd,p,size);
        printf("The content is %s\n",p);
        if(strcmp(p,"quit")==0)
        {
            free(p);
            p=NULL;
            break;
        }
        free(p);
        p=NULL;
    }
    
    printf("The buf is %s\n",buf);
    close(rfd);
    rfd = -1;
    return 0;
}
char *MyGetString(char*pbuf,int size)
{
    char *p=NULL;
    int len=0;
    p = fgets(pbuf,size,stdin);
    if(NULL==p)
    {
        return NULL;
    }
    //判断用户本次输入有剩余
    len=strlen(pbuf);
    if(*(pbuf+len-1)=='\n')
    {
        *(pbuf+len-1)='\0';
    }
    else
    {
        while(getchar()!='\n')
        {

        }
    }
    return p;
}